from PyQt5.QtCore import Qt, QPropertyAnimation, pyqtProperty, pyqtSignal, QEasingCurve
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtGui import QPainter, QColor


class Switch(QWidget):
    toggled = pyqtSignal(bool)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedSize(60, 30)
        self._checked = False
        self._bg_color = QColor("#c5c5c5")
        self._circle_color = QColor("#ffffff")
        self._circle_position = 2

        self.animation = QPropertyAnimation(self, b"circle_position")
        self.animation.setDuration(200)
        # 关键修改：使用QEasingCurve代替Qt.EasingCurve
        self.animation.setEasingCurve(QEasingCurve.OutQuad)  # 修正这里

        self.checked = True

    # 正确定义动态属性
    def get_circle_position(self):
        return self._circle_position

    def set_circle_position(self, pos):
        self._circle_position = pos
        self.update()  # 触发重绘

    circle_position = pyqtProperty(int, get_circle_position, set_circle_position)

    @property
    def checked(self):
        return self._checked

    @checked.setter
    def checked(self, value):
        if self._checked != value:
            self._checked = value
            self.toggled.emit(value)
            self.start_animation()

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 绘制背景
        bg_color = QColor("#4cd964" if self.checked else "#c5c5c5")
        painter.setBrush(bg_color)
        painter.drawRoundedRect(0, 0, self.width(), self.height(), 15, 15)

        # 绘制滑块
        painter.setBrush(self._circle_color)
        painter.drawEllipse(self._circle_position, 2, 26, 26)

    def mousePressEvent(self, event):
        self.checked = not self.checked  # 切换状态

    def start_animation(self):
        self.animation.stop()
        target_pos = 32 if self.checked else 2
        self.animation.setStartValue(self.circle_position)
        self.animation.setEndValue(target_pos)
        self.animation.start()


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    switch = Switch()
    switch.show()
    sys.exit(app.exec_())